package com.gty.lolutil;

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class BaseUtil {
    public static String HERO_ID;
    //得到响应的json数据
    public static String getJson(InputStream inputStream){
        BufferedInputStream br = new BufferedInputStream(inputStream);
        try{
            StringBuilder sb = new StringBuilder();
            int len=0;
            byte[] b=new byte[128];

            while((len=br.read(b))!=-1){
                sb.append(new String(b,0,len,"UTF-8"));
            }
            return sb.toString();
        }catch (Exception e){

        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";



    }


    //跳过SSL证书
    public static CloseableHttpClient getIgnoreSSLClient(String password, int port) throws Exception {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();

        //创建httpClient
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        Credentials credentials = new UsernamePasswordCredentials("riot", password);
        credentialsProvider.setCredentials(new AuthScope("127.0.0.1", port), credentials);

        CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).
                setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setDefaultCredentialsProvider(credentialsProvider)//设置auth
                .build();
        return client;
    }
}
